package com.gxa.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.gxa.common.base.LayuiResultJson;
import com.gxa.common.base.Result;
import com.gxa.common.constant.Constants;
import com.gxa.common.utils.MD5Utils;
import com.gxa.domain.dto.FindUserByNameDTO;
import com.gxa.domain.dto.LoginFormDTO;
import com.gxa.domain.entity.User;
import com.gxa.domain.vo.FindUserByNameVO;
import com.gxa.domain.vo.LoginUserInfoVO;
import com.gxa.mapper.UserMapper;
import com.gxa.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    // 日志对象
    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserMapper userMapper;
    @Override
    public User findUserById(int userId) {
        User user = new User();
        user = userMapper.queryById(userId);
        System.out.println("查询结果："+user);
        return user;
    }

    @Override
    public Result login(LoginFormDTO loginFormDTO) {
        logger.info("{}用户进行登录请求",loginFormDTO.getUsername());
//         加密
        String newPwd = MD5Utils.encrypt(loginFormDTO.getPassword());
        User user = userMapper.findUserByUsername(loginFormDTO.getUsername());
        if(user != null && user.getPassword().equals(newPwd)){
//            更改用户最后一次登录时间
            System.out.println(user);
            System.out.println("登录次数="+user.getLoginCount());
            int userLoginCount = user.getLoginCount();
            userLoginCount++;
            userMapper.upLastLoginTime(userLoginCount,new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss").format(new Date()));
            // 对象拷贝
            LoginUserInfoVO loginUserInfoVO =  BeanUtil.copyProperties(user,LoginUserInfoVO.class);
            return Result.success("登录成功",loginUserInfoVO);
        }else{
            logger.error("账户{}或密码{}有误",loginFormDTO.getUsername(),loginFormDTO.getPassword());
            return Result.error("账户或密码有误");
        }
    }

    @Override
    public LayuiResultJson findUserByName(String title, int page, int limit) {
        Integer offset = (page - 1)*limit;
        Integer rows = limit;
        List<FindUserByNameVO> findUserByNameVO= userMapper.findUserByName(title,offset,rows);
        Integer totalSize = userMapper.countSysUserByCondition(title);
        LayuiResultJson layuiResultJson = new LayuiResultJson();

        layuiResultJson.setCode(Constants.OK);
        layuiResultJson.setMsg(Constants.MESSAGE_OK);
        layuiResultJson.setCount(totalSize);
        layuiResultJson.setData(findUserByNameVO);

        return layuiResultJson;
    }

    @Override //重写接口方法
    public Result add(User user) {
        int i =  userMapper.add(user);  //调用add方法执行数据库插入，返回在i变量中
        return null;
    }


}
